#include "UdpServer.hpp"
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <string>
#include <vector>
#include <memory>

using namespace std;

void Usage(const string& proc)
{
    // cout << proc << " localip localport\n" << endl;
    cout << proc << " localport\n" << endl;
}

string DefalutMessage(string message)
{
    return message + " [I've already gotten the information.]";
}

vector<string> black_list{
    "rm" , "cp" , "mv" , "top" , "vim" , "vi" , "nano" , "kill"
};

bool IsSafe(const string &message)
{
    size_t pos = 0;
    for(auto v : black_list)
    {
        pos = message.find(v);
        if(pos != string::npos)
            return false;
    }
    return true;
}

string ExecuteCommand(string message)
{
    if(!IsSafe(message))
    {
        return "Prohibited Command";
    }
    FILE* fp = popen(message.c_str(),"r");
    if(!fp)
        return "Unknown command";

    char buffer[1024];
    string response;
    while(1)
    {
        if(!fgets(buffer,1023,fp))
            break;
        response+=buffer;
    }

    fclose(fp);
    return response;
}

// ./udpserver localip localport
int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }

    uint16_t port = stoi(argv[1]);
    // unique_ptr<UdpServer> uq = make_unique<UdpServer>(DefalutMessage,port);
    unique_ptr<UdpServer> uq = make_unique<UdpServer>(ExecuteCommand,port);

    uq->Init();
    uq->Start();

    return 0;
}